package com.xywang.servlet.bill;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.xywang.pojo.Bill;
import com.xywang.pojo.Provider;
import com.xywang.pojo.User;
import com.xywang.service.bill.BillService;
import com.xywang.service.bill.BillServiceImpl;
import com.xywang.service.provider.ProviderService;
import com.xywang.service.provider.ProviderServiceImpl;
import com.xywang.util.Constants;
import com.xywang.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class ServletBill extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method != null && method.equals("query")) {
            this.query(req, resp);
        }else if(method != null && method.equals("add")){
            this.add(req, resp);
        }else if (method != null && method.equals("getproviderlist")) {
           this.getProviderlist(req, resp);
        }else if (method != null && method.equals("delbill")) {
            this.delBill(req, resp);
        }else if (method != null && method.equals("modify")) {
            this.getBillByIdModify(req, resp);
        }else if (method != null && method.equals("modifysave")) {
            this.modify(req, resp);
        }else if (method != null && method.equals("view")) {
            this.getBillById(req, resp);
       }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 展示订单
    public void query(HttpServletRequest req, HttpServletResponse resp){
        // 创建服务层对象，之后调用他们的方法
        BillService billService = new BillServiceImpl();
        ProviderService providerService = new ProviderServiceImpl();

        // 获取前端数据
        String queryProductName = req.getParameter("queryProductName");
        String queryProviderId = req.getParameter("queryProviderId");
        String queryIsPayment = req.getParameter("queryIsPayment");
        String pageIndex = req.getParameter("pageIndex");

        // 将前端获取的参数做判断后封装到bill对象中
        Bill bill = new Bill();

        if (StringUtils.isNullOrEmpty(queryProductName)) {
            queryProductName = "";
        }
        bill.setProductName(queryProductName);
        if (StringUtils.isNullOrEmpty(queryIsPayment)) {
            bill.setIsPayment(0);
        } else {
            bill.setIsPayment(Integer.parseInt(queryIsPayment));
        }
        if (StringUtils.isNullOrEmpty(queryProviderId)) {
            bill.setProviderId(0);
        } else {
            bill.setProviderId(Integer.parseInt(queryProviderId));
        }

        // 实现分页
        // 第一次走这个请求，一定是第一页，页面大小固定的
        int pageSize = 5;// 可以把这个写到配置文件中，方便后期修改：
        int currentPageNo=1;
        // 当前‘页’
        if (pageIndex != null) {
            try{
                currentPageNo = Integer.parseInt(pageIndex);
            }catch (Exception e){
                try {
                    resp.sendRedirect(req.getContextPath()+"/error.jsp");
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
        // 获取订单总条数 (分页 ：上一页，下一页)
        int userTotalCount = billService.getBillCountService(bill);
        // 调用分页算法工具类
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(userTotalCount);
        // 总页数 getTotalPageCount()
        int totalPageCount = pageSupport.getTotalPageCount();
        // 控制首页和尾页
        if(currentPageNo<1){
            currentPageNo = 1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo = totalPageCount;
        }

        // 获取供应商列表，输出到前端
        List<Provider> providerList;
        providerList = providerService.getProviderListService("", "");

        // 获取订单列表
        List<Bill> billList;
        billList = billService.getBillList(bill, currentPageNo, pageSize);

        // 像前端发送数据
        req.setAttribute("totalCount",userTotalCount);// 用户总数
        req.setAttribute("currentPageNo",currentPageNo);// 当前页
        req.setAttribute("totalPageCount",totalPageCount);// 总页数

        req.setAttribute("providerList", providerList);
        req.setAttribute("billList", billList);
        req.setAttribute("queryProductName", queryProductName);
        req.setAttribute("queryProviderId", queryProviderId);
        req.setAttribute("queryIsPayment", queryIsPayment);
        try {
            req.getRequestDispatcher("billlist.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    // 添加订单
    public void add(HttpServletRequest req, HttpServletResponse resp){
        String billCode = req.getParameter("billCode");// 订单编码
        String productName = req.getParameter("productName");// 商品名称
        String productDesc = req.getParameter("productDesc");// 商品描述
        String productUnit = req.getParameter("productUnit");// 商品单位

        String productCount = req.getParameter("productCount");// 商品数量
        String totalPrice = req.getParameter("totalPrice");// 总金额
        String providerId = req.getParameter("providerId");// 供应商
        String isPayment = req.getParameter("isPayment");// 是否付款


        Bill bill = new Bill();
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductDesc(productDesc);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount).setScale(2, BigDecimal.ROUND_DOWN));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN));
        bill.setProviderId(Integer.parseInt(providerId));
        bill.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setCreationDate(new Date());

        boolean flag = false;
        BillService billService = new BillServiceImpl();
        flag = billService.add(bill);
        if (flag) {
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/bill.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                req.getRequestDispatcher("billadd.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 获取供应商列表
    public void getProviderlist(HttpServletRequest req, HttpServletResponse resp){
        List<Provider> providerList = new ArrayList<Provider>();
        ProviderService providerService = new ProviderServiceImpl();
        providerList = providerService.getProviderListService("", "");

        //把providerList转换成json对象输出
        PrintWriter outPrintWriter = null;
        try {
            resp.setContentType("application/json");
            outPrintWriter = resp.getWriter();
            outPrintWriter.write(JSONArray.toJSONString(providerList));
            outPrintWriter.flush();
            outPrintWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 删除订单
    public void delBill(HttpServletRequest req, HttpServletResponse resp){
        String billid = req.getParameter("billid");
        int delId = 0;
        try {
            delId = Integer.parseInt(billid);
        } catch (Exception e) {
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            BillServiceImpl billService = new BillServiceImpl();
            if (billService.deleteBillById(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }

        //把resultMap转换成json对象输出
        PrintWriter outPrintWriter = null;
        try {
            resp.setContentType("application/json");
            outPrintWriter = resp.getWriter();
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();
            outPrintWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 获取订单
    public void getBillByIdModify(HttpServletRequest req, HttpServletResponse resp){
        String billid = req.getParameter("billid");
        if (!StringUtils.isNullOrEmpty(billid)) {
            //调用后台方法得到bill对象
            BillServiceImpl billService = new BillServiceImpl();
            Bill bill = billService.getBillByIdService(Integer.parseInt(billid));
            req.setAttribute("bill", bill);
            try {
                req.getRequestDispatcher("billmodify.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 修改订单
    public void modify(HttpServletRequest req, HttpServletResponse resp){
        // 从billmodify.jsp获取数据
        String id = req.getParameter("id");
        String productName = req.getParameter("productName");
        String productDesc = req.getParameter("productDesc");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");


        Bill bill = new Bill();
        bill.setId(Integer.valueOf(id));
        bill.setProductName(productName);
        bill.setProductDesc(productDesc);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount).setScale(2, BigDecimal.ROUND_DOWN));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN));
        bill.setProviderId(Integer.parseInt(providerId));

        bill.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setModifyDate(new Date());
        boolean flag = false;
        BillService billService = new BillServiceImpl();
        flag = billService.modify(bill);
        if (flag) {
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/bill.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                req.getRequestDispatcher("billmodify.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 展示订单
    public void getBillById(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("billid");
        if (!StringUtils.isNullOrEmpty(id)) {
            BillService billService = new BillServiceImpl();
            Bill bill = null;
            bill = billService.getBillByIdService(Integer.parseInt(id));
            req.setAttribute("bill", bill);
            try {
                req.getRequestDispatcher("billview.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }

}

